package com.cocostudio.erpapp;

import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import androidx.fragment.app.DialogFragment;
import androidx.fragment.app.FragmentManager;
import androidx.loader.content.AsyncTaskLoader;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class LoadingFragment extends DialogFragment {
    private AsyncTask<?, ?, ?> heldTask;
    private AsyncTaskLoader<?> heldLoader;
    private static LoadingFragment loadingFragment;

    public static void show(FragmentManager fragmentManager) {
        loadingFragment = new LoadingFragment();
        loadingFragment.show(fragmentManager, "loading");
    }

    public static void show(FragmentManager fragmentManager, AsyncTask<?, ?, ?> task) {
        loadingFragment = new LoadingFragment(task);
        loadingFragment.show(fragmentManager, "loading");
    }

    public static void show(FragmentManager fragmentManager, AsyncTaskLoader<?> loader) {
        loadingFragment = new LoadingFragment(loader);
        loadingFragment.show(fragmentManager, "loading");
    }

    public static void dismiss(FragmentManager fragmentManager) {
        if (loadingFragment != null) {
            loadingFragment.dismiss();
            loadingFragment = null;
        }
    }

    public static void dismiss(FragmentManager fragmentManager, Handler handler) {
        handler.post(new Runnable() {
            @Override
            public void run() {
                if (loadingFragment != null) {
                    loadingFragment.dismiss();
                    loadingFragment = null;
                }
            }
        });

    }

    private LoadingFragment() {
    }

    private LoadingFragment(AsyncTaskLoader<?> loader) {
        heldLoader = loader;
    }

    private LoadingFragment(AsyncTask<?, ?, ?> task) {
        heldTask = task;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStyle(DialogFragment.STYLE_NO_FRAME, 0);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_loading, container);
    }

    @Override
    public void onCancel(DialogInterface dialog) {
        if (heldLoader != null) {
            heldLoader.cancelLoad();
        }
        if (heldTask != null) {
            heldTask.cancel(true);
        }
    }
}
